package com.inheritance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inheritance.entity.Banner;
import com.inheritance.mapper.BannerMapper;
import com.inheritance.service.BannerService;
import com.inheritance.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    @Resource
    private BannerMapper bannerMapper;


    @Override
    public Boolean upload(MultipartFile file) {
        // 1. 判空处理
        if (file.isEmpty()) {
            return false;
        }
        // 获取文件后缀
        String suffix;
        if (file.getOriginalFilename() != null) {
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            try {
                // 4. 生成文件名
                String fileName = UUID.randomUUID() + suffix;
                // 5. 上传文件
                String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
                int i = bannerMapper.insert(new Banner().setUrl(url));
                return i > 0;
            } catch (IOException e) {
                log.info(e.getMessage());
                return false;
            }
        }
        return false;
    }

    @Override
    public List<Banner> list() {
        return bannerMapper.selectList(null);
    }

    @Override
    public int delete(String id) {
        return bannerMapper.deleteById(id);
    }
}
